package com.xyzwps.harbor.service;

import com.xyzwps.harbor.model.UserPassword;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

@Service
public class SimplePasswordCrypto implements PasswordCrypto {

    @Override
    public String encrypt(long userId, String realPassword) {
        return this.encryptWithSalt(userId, realPassword, this.randomSalt());
    }

    @Override
    public boolean check(UserPassword userPassword, String realPassword) {
        return userPassword.getEncryptedPassword().equals(this.encryptWithSalt(
                userPassword.getUserId(),
                realPassword,
                userPassword.getEncryptedPassword().substring(0, SALT_LEN)
        ));
    }

    String encryptWithSalt(long userId, String realPassword, String salt) {
        var t1 = DigestUtils.sha1Hex(salt + realPassword + userId);
        var t2 = DigestUtils.sha1Hex(salt + t1 + userId);
        return salt + t2;
    }

    String randomSalt() {
        return RandomStringUtils.randomAlphanumeric(SALT_LEN);
    }

    public static final int SALT_LEN = 31;
}